package com.gopay.common.oldmermove.util;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * 商户识别码解密
 * @IdentityCodeUtil.java
 * @author lizheng
 * @2014-7-29 下午4:05:34  www.gopay.com.cn Inc.All rights reserved.
 */
public class IdentityCodeUtil {

	/** logger. */
	private static final Logger logger = Logger.getLogger(IdentityCodeUtil.class);
	
	/** 商户识别码密钥KEY. */
	private static final String IDENTITY_CODE_KEY_MERCHANT = "524fc246c761efd5";

	/** 企业识别码密钥KEY. */
	private static final String IDENTITY_CODE_KEY_CORP = "e57a8379c280cba8";

	private static final String IDENTITY_CODE_NOT_ENCRYPT = "0";
	private static final String IDENTITY_CODE_HAVE_ENCRYPT = "1";

	/**
	 * 返回商户识别码
	 * @param identityCode
	 * @param identityCodeHaveEncrypt
	 * @return
	 * @throws Exception
	 */
	public static String getCode4Merchant(String identityCode,String identityCodeHaveEncrypt) throws Exception {
		/* 如果为空，直接返回 */
		if (StringUtils.isEmpty(identityCode)) {
			return identityCode;
		}
		/* 识别码没有加密直接返回 */
		if (IDENTITY_CODE_NOT_ENCRYPT.equals(identityCodeHaveEncrypt)
				|| StringUtils.isEmpty(identityCodeHaveEncrypt)) {
			identityCode = StringUtils.trimToEmpty(identityCode);
		} else if (IDENTITY_CODE_HAVE_ENCRYPT.equals(identityCodeHaveEncrypt)) {
				/* 识别码已加密进行解密后再返回 */
				identityCode = DESUtil.decrypt(StringUtils.trimToEmpty(identityCode),
						IDENTITY_CODE_KEY_MERCHANT);
		}

		return StringUtils.trimToEmpty(identityCode);
	}
	
	/**
	 * 返回企业的识别码
	 * 
	 * @param identityCode
	 *            企业识别码原文
	 * @return
	 */
	public static String getCode4Corp(Object identityCodeObj) {
		String identityCode = "";
		if (identityCodeObj == null || StringUtils.isEmpty(identityCodeObj.toString())) {
			return identityCode;
		}

		try {
			/* 识别码已加密进行解密后再返回 */
			identityCode = DESUtil.decrypt(StringUtils.trimToEmpty(identityCodeObj.toString()), IDENTITY_CODE_KEY_CORP);
		} catch (Exception e) {
			logger.error("企业付款识别码解密失败  IdentityCode:" + identityCodeObj);
			e.printStackTrace();
		}

		return identityCode;
	}
}